# Copyright 2025 Stability AI and The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import inspect
from typing import Callable, List, Optional, Union

from numpy import copy
import torch
from transformers import (
    T5EncoderModel,
    T5Tokenizer,
    T5TokenizerFast,
)

from ...models import AutoencoderOobleck, StableAudioDiTModel
from ...models.embeddings import get_1d_rotary_pos_embed
# from ...schedulers import EDMDPMSolverMultistepScheduler
# from ...schedulers import CosineDPMSolverMultistepScheduler
from ...schedulers import scheduling_cosine_dpmsolver_multistep_reverse
from ...schedulers import CosineDPMSolverMultistepScheduler
from ...utils import (
    is_torch_xla_available,
    logging,
    replace_example_docstring,
)
from ...utils.torch_utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline
from .modeling_stable_audio import StableAudioProjectionModel
import torch.nn.functional as F


if is_torch_xla_available():
    import torch_xla.core.xla_model as xm

    XLA_AVAILABLE = True
else:
    XLA_AVAILABLE = False

logger = logging.get_logger(__name__)  # pylint: disable=invalid-name

EXAMPLE_DOC_STRING = """
    Examples:
        ```py
        >>> import scipy
        >>> import torch
        >>> import soundfile as sf
        >>> from diffusers import StableAudioPipeline

        >>> repo_id = "stabilityai/stable-audio-open-1.0"
        >>> pipe = StableAudioPipeline.from_pretrained(repo_id, torch_dtype=torch.float16)
        >>> pipe = pipe.to("cuda")

        >>> # define the prompts
        >>> prompt = "The sound of a hammer hitting a wooden surface."
        >>> negative_prompt = "Low quality."

        >>> # set the seed for generator
        >>> generator = torch.Generator("cuda").manual_seed(0)

        >>> # run the generation
        >>> audio = pipe(
        ...     prompt,
        ...     negative_prompt=negative_prompt,
        ...     num_inference_steps=200,
        ...     audio_end_in_s=10.0,
        ...     num_waveforms_per_prompt=3,
        ...     generator=generator,
        ... ).audios

        >>> output = audio[0].T.float().cpu().numpy()
        >>> sf.write("hammer.wav", output, pipe.vae.sampling_rate)
        ```
"""


class StableAudioRenoiseInversionPipeline(DiffusionPipeline):
    r"""
    Pipeline for text-to-audio generation using StableAudio.

    This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
    implemented for all pipelines (downloading, saving, running on a particular device, etc.).

    Args:
        vae ([`AutoencoderOobleck`]):
            Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
        text_encoder ([`~transformers.T5EncoderModel`]):
            Frozen text-encoder. StableAudio uses the encoder of
            [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
            [google-t5/t5-base](https://huggingface.co/google-t5/t5-base) variant.
        projection_model ([`StableAudioProjectionModel`]):
            A trained model used to linearly project the hidden-states from the text encoder model and the start and
            end seconds. The projected hidden-states from the encoder and the conditional seconds are concatenated to
            give the input to the transformer model.
        tokenizer ([`~transformers.T5Tokenizer`]):
            Tokenizer to tokenize text for the frozen text-encoder.
        transformer ([`StableAudioDiTModel`]):
            A `StableAudioDiTModel` to denoise the encoded audio latents.
        scheduler ([`EDMDPMSolverMultistepScheduler`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded audio latents.
    """

    model_cpu_offload_seq = "text_encoder->projection_model->transformer->vae"

    def __init__(
        self,
        vae: AutoencoderOobleck,
        text_encoder: T5EncoderModel,
        projection_model: StableAudioProjectionModel,
        tokenizer: Union[T5Tokenizer, T5TokenizerFast],
        transformer: StableAudioDiTModel,
        scheduler: scheduling_cosine_dpmsolver_multistep_reverse, # EDMDPMSolverMultistepScheduler default CosineDPMSolverMultistepScheduler 
        denoise_scheduler: Optional[CosineDPMSolverMultistepScheduler] = CosineDPMSolverMultistepScheduler(),  # 新增
    ):
        super().__init__()
        
        self.register_modules(
            vae=vae,
            text_encoder=text_encoder,
            projection_model=projection_model,
            tokenizer=tokenizer,
            transformer=transformer,
            scheduler=scheduler,
            denoise_scheduler = denoise_scheduler,
        )
        self.scheduler = scheduler  # 直接赋值 不传入register工厂[_d]
        self.rotary_embed_dim = self.transformer.config.attention_head_dim // 2


    # Copied from diffusers.pipelines.pipeline_utils.StableDiffusionMixin.enable_vae_slicing
    def enable_vae_slicing(self):
        r"""
        Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
        compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
        """
        self.vae.enable_slicing()

    # Copied from diffusers.pipelines.pipeline_utils.StableDiffusionMixin.disable_vae_slicing
    def disable_vae_slicing(self):
        r"""
        Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
        computing decoding in one step.
        """
        self.vae.disable_slicing()

    def encode_prompt(
        self,
        prompt,
        device,
        do_classifier_free_guidance,
        negative_prompt=None,
        prompt_embeds: Optional[torch.Tensor] = None,
        negative_prompt_embeds: Optional[torch.Tensor] = None,
        attention_mask: Optional[torch.LongTensor] = None,
        negative_attention_mask: Optional[torch.LongTensor] = None,
    ):
        if prompt is not None and isinstance(prompt, str):
            batch_size = 1
        elif prompt is not None and isinstance(prompt, list):
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]

        if prompt_embeds is None:
            # 1. Tokenize text
            text_inputs = self.tokenizer(
                prompt,
                padding="max_length",
                max_length=self.tokenizer.model_max_length,
                truncation=True,
                return_tensors="pt",
            )
            text_input_ids = text_inputs.input_ids
            attention_mask = text_inputs.attention_mask
            untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids

            if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
                text_input_ids, untruncated_ids
            ):
                removed_text = self.tokenizer.batch_decode(
                    untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
                )
                logger.warning(
                    f"The following part of your input was truncated because {self.text_encoder.config.model_type} can "
                    f"only handle sequences up to {self.tokenizer.model_max_length} tokens: {removed_text}"
                )

            text_input_ids = text_input_ids.to(device)
            attention_mask = attention_mask.to(device)

            # 2. Text encoder forward
            self.text_encoder.eval()
            prompt_embeds = self.text_encoder(
                text_input_ids,
                attention_mask=attention_mask,
            )
            prompt_embeds = prompt_embeds[0]

        if do_classifier_free_guidance and negative_prompt is not None:
            uncond_tokens: List[str]
            if type(prompt) is not type(negative_prompt):
                raise TypeError(
                    f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
                    f" {type(prompt)}."
                )
            elif isinstance(negative_prompt, str):
                uncond_tokens = [negative_prompt]
            elif batch_size != len(negative_prompt):
                raise ValueError(
                    f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
                    f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                    " the batch size of `prompt`."
                )
            else:
                uncond_tokens = negative_prompt

            # 1. Tokenize text
            uncond_input = self.tokenizer(
                uncond_tokens,
                padding="max_length",
                max_length=self.tokenizer.model_max_length,
                truncation=True,
                return_tensors="pt",
            )

            uncond_input_ids = uncond_input.input_ids.to(device)
            negative_attention_mask = uncond_input.attention_mask.to(device)

            # 2. Text encoder forward
            self.text_encoder.eval()
            negative_prompt_embeds = self.text_encoder(
                uncond_input_ids,
                attention_mask=negative_attention_mask,
            )
            negative_prompt_embeds = negative_prompt_embeds[0]

            if negative_attention_mask is not None:
                # set the masked tokens to the null embed
                negative_prompt_embeds = torch.where(
                    negative_attention_mask.to(torch.bool).unsqueeze(2), negative_prompt_embeds, 0.0
                )

        # 3. Project prompt_embeds and negative_prompt_embeds
        if do_classifier_free_guidance and negative_prompt_embeds is not None:
            # For classifier free guidance, we need to do two forward passes.
            # Here we concatenate the negative and text embeddings into a single batch
            # to avoid doing two forward passes
            prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
            if attention_mask is not None and negative_attention_mask is None:
                negative_attention_mask = torch.ones_like(attention_mask)
            elif attention_mask is None and negative_attention_mask is not None:
                attention_mask = torch.ones_like(negative_attention_mask)

            if attention_mask is not None:
                attention_mask = torch.cat([negative_attention_mask, attention_mask])

        prompt_embeds = self.projection_model(
            text_hidden_states=prompt_embeds,
        ).text_hidden_states
        if attention_mask is not None:
            prompt_embeds = prompt_embeds * attention_mask.unsqueeze(-1).to(prompt_embeds.dtype)
            prompt_embeds = prompt_embeds * attention_mask.unsqueeze(-1).to(prompt_embeds.dtype)

        return prompt_embeds

    def encode_duration(
        self,
        audio_start_in_s,
        audio_end_in_s,
        device,
        do_classifier_free_guidance,
        batch_size,
    ):
        audio_start_in_s = audio_start_in_s if isinstance(audio_start_in_s, list) else [audio_start_in_s]
        audio_end_in_s = audio_end_in_s if isinstance(audio_end_in_s, list) else [audio_end_in_s]

        if len(audio_start_in_s) == 1:
            audio_start_in_s = audio_start_in_s * batch_size
        if len(audio_end_in_s) == 1:
            audio_end_in_s = audio_end_in_s * batch_size

        # Cast the inputs to floats
        audio_start_in_s = [float(x) for x in audio_start_in_s]
        audio_start_in_s = torch.tensor(audio_start_in_s).to(device)

        audio_end_in_s = [float(x) for x in audio_end_in_s]
        audio_end_in_s = torch.tensor(audio_end_in_s).to(device)

        projection_output = self.projection_model(
            start_seconds=audio_start_in_s,
            end_seconds=audio_end_in_s,
        )
        seconds_start_hidden_states = projection_output.seconds_start_hidden_states
        seconds_end_hidden_states = projection_output.seconds_end_hidden_states

        # For classifier free guidance, we need to do two forward passes.
        # Here we repeat the audio hidden states to avoid doing two forward passes
        if do_classifier_free_guidance:
            seconds_start_hidden_states = torch.cat([seconds_start_hidden_states, seconds_start_hidden_states], dim=0)
            seconds_end_hidden_states = torch.cat([seconds_end_hidden_states, seconds_end_hidden_states], dim=0)

        return seconds_start_hidden_states, seconds_end_hidden_states

    # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
    def prepare_extra_step_kwargs(self, generator, eta):
        # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
        # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
        # eta corresponds to η in DDIM paper: https://huggingface.co/papers/2010.02502
        # and should be between [0, 1]

        accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
        extra_step_kwargs = {}
        if accepts_eta:
            extra_step_kwargs["eta"] = eta

        # check if the scheduler accepts generator
        accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
        if accepts_generator:
            extra_step_kwargs["generator"] = generator
        return extra_step_kwargs

    def check_inputs(
        self,
        prompt,
        audio_start_in_s,
        audio_end_in_s,
        callback_steps,
        negative_prompt=None,
        prompt_embeds=None,
        negative_prompt_embeds=None,
        attention_mask=None,
        negative_attention_mask=None,
        initial_audio_waveforms=None,
        initial_audio_sampling_rate=None,
    ):
        if audio_end_in_s < audio_start_in_s:
            raise ValueError(
                f"`audio_end_in_s={audio_end_in_s}' must be higher than 'audio_start_in_s={audio_start_in_s}` but "
            )

        if (
            audio_start_in_s < self.projection_model.config.min_value
            or audio_start_in_s > self.projection_model.config.max_value
        ):
            raise ValueError(
                f"`audio_start_in_s` must be greater than or equal to {self.projection_model.config.min_value}, and lower than or equal to {self.projection_model.config.max_value} but "
                f"is {audio_start_in_s}."
            )

        if (
            audio_end_in_s < self.projection_model.config.min_value
            or audio_end_in_s > self.projection_model.config.max_value
        ):
            raise ValueError(
                f"`audio_end_in_s` must be greater than or equal to {self.projection_model.config.min_value}, and lower than or equal to {self.projection_model.config.max_value} but "
                f"is {audio_end_in_s}."
            )

        if (callback_steps is None) or (
            callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
        ):
            raise ValueError(
                f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
                f" {type(callback_steps)}."
            )

        if prompt is not None and prompt_embeds is not None:
            raise ValueError(
                f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
                " only forward one of the two."
            )
        elif prompt is None and (prompt_embeds is None):
            raise ValueError(
                "Provide either `prompt`, or `prompt_embeds`. Cannot leave"
                "`prompt` undefined without specifying `prompt_embeds`."
            )
        elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
            raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")

        if negative_prompt is not None and negative_prompt_embeds is not None:
            raise ValueError(
                f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
                f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
            )

        if prompt_embeds is not None and negative_prompt_embeds is not None:
            if prompt_embeds.shape != negative_prompt_embeds.shape:
                raise ValueError(
                    "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
                    f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
                    f" {negative_prompt_embeds.shape}."
                )
            if attention_mask is not None and attention_mask.shape != prompt_embeds.shape[:2]:
                raise ValueError(
                    "`attention_mask should have the same batch size and sequence length as `prompt_embeds`, but got:"
                    f"`attention_mask: {attention_mask.shape} != `prompt_embeds` {prompt_embeds.shape}"
                )

        if initial_audio_sampling_rate is None and initial_audio_waveforms is not None:
            raise ValueError(
                "`initial_audio_waveforms' is provided but the sampling rate is not. Make sure to pass `initial_audio_sampling_rate`."
            )

        if initial_audio_sampling_rate is not None and initial_audio_sampling_rate != self.vae.sampling_rate:
            raise ValueError(
                f"`initial_audio_sampling_rate` must be {self.vae.hop_length}' but is `{initial_audio_sampling_rate}`."
                "Make sure to resample the `initial_audio_waveforms` and to correct the sampling rate. "
            )

    def prepare_latents(
        self,
        batch_size,
        num_channels_vae,
        sample_size,
        dtype,
        device,
        generator,
        latents=None,
        initial_audio_waveforms=None,
        num_waveforms_per_prompt=None,
        audio_channels=None,
    ):
        shape = (batch_size, num_channels_vae, sample_size)
        if isinstance(generator, list) and len(generator) != batch_size:
            raise ValueError(
                f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
                f" size of {batch_size}. Make sure the batch size matches the length of the generators."
            )
            
        if latents is None:
            latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
        else:
            latents = latents.to(device)

        # scale the initial noise by the standard deviation required by the scheduler
        # latents = latents * self.scheduler.init_noise_sigma
        # 在inversion模式下，保存 initial noise
        # torch.save(latents, "original_noise.pt")

        # encode the initial audio for use by the model
        if initial_audio_waveforms is not None:
            # check dimension
            if initial_audio_waveforms.ndim == 2:
                initial_audio_waveforms = initial_audio_waveforms.unsqueeze(1)
            elif initial_audio_waveforms.ndim != 3:
                raise ValueError(
                    f"`initial_audio_waveforms` must be of shape `(batch_size, num_channels, audio_length)` or `(batch_size, audio_length)` but has `{initial_audio_waveforms.ndim}` dimensions"
                )

            audio_vae_length = int(self.transformer.config.sample_size) * self.vae.hop_length
            audio_shape = (batch_size // num_waveforms_per_prompt, audio_channels, audio_vae_length)

            # check num_channels
            if initial_audio_waveforms.shape[1] == 1 and audio_channels == 2:
                initial_audio_waveforms = initial_audio_waveforms.repeat(1, 2, 1)
            elif initial_audio_waveforms.shape[1] == 2 and audio_channels == 1:
                initial_audio_waveforms = initial_audio_waveforms.mean(1, keepdim=True)

            if initial_audio_waveforms.shape[:2] != audio_shape[:2]:
                raise ValueError(
                    f"`initial_audio_waveforms` must be of shape `(batch_size, num_channels, audio_length)` or `(batch_size, audio_length)` but is of shape `{initial_audio_waveforms.shape}`"
                )

            # crop or pad
            audio_length = initial_audio_waveforms.shape[-1]
            if audio_length < audio_vae_length:
                logger.warning(
                    f"The provided input waveform is shorter ({audio_length}) than the required audio length ({audio_vae_length}) of the model and will thus be padded."
                )
            elif audio_length > audio_vae_length:
                logger.warning(
                    f"The provided input waveform is longer ({audio_length}) than the required audio length ({audio_vae_length}) of the model and will thus be cropped."
                )

            audio = initial_audio_waveforms.new_zeros(audio_shape)
            audio[:, :, : min(audio_length, audio_vae_length)] = initial_audio_waveforms[:, :, :audio_vae_length]

            encoded_audio = self.vae.encode(audio).latent_dist.sample(generator)
            encoded_audio = encoded_audio.repeat((num_waveforms_per_prompt, 1, 1))
            latents = encoded_audio + latents
        return latents

    # @torch.no_grad()
    @replace_example_docstring(EXAMPLE_DOC_STRING)
    def __call__(
        self,
        prompt: Union[str, List[str]] = None,
        audio_end_in_s: Optional[float] = None,
        audio_start_in_s: Optional[float] = 0.0,
        num_inference_steps: int = 100,
        guidance_scale: float = 7.0,
        negative_prompt: Optional[Union[str, List[str]]] = None,
        num_waveforms_per_prompt: Optional[int] = 1,
        eta: float = 0.0,
        generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
        latents: Optional[torch.Tensor] = None,
        initial_audio_waveforms: Optional[torch.Tensor] = None,
        initial_audio_sampling_rate: Optional[torch.Tensor] = None,
        prompt_embeds: Optional[torch.Tensor] = None,
        negative_prompt_embeds: Optional[torch.Tensor] = None,
        attention_mask: Optional[torch.LongTensor] = None,
        negative_attention_mask: Optional[torch.LongTensor] = None,
        return_dict: bool = True,
        callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
        callback_steps: Optional[int] = 1,
        output_type: Optional[str] = "pt",
    ):
        r"""
        The call function to the pipeline for generation.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide audio generation. If not defined, you need to pass `prompt_embeds`.
            audio_end_in_s (`float`, *optional*, defaults to 47.55):
                Audio end index in seconds.
            audio_start_in_s (`float`, *optional*, defaults to 0):
                Audio start index in seconds.
            num_inference_steps (`int`, *optional*, defaults to 100):
                The number of denoising steps. More denoising steps usually lead to a higher quality audio at the
                expense of slower inference.
            guidance_scale (`float`, *optional*, defaults to 7.0):
                A higher guidance scale value encourages the model to generate audio that is closely linked to the text
                `prompt` at the expense of lower sound quality. Guidance scale is enabled when `guidance_scale > 1`.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide what to not include in audio generation. If not defined, you need to
                pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
            num_waveforms_per_prompt (`int`, *optional*, defaults to 1):
                The number of waveforms to generate per prompt.
            eta (`float`, *optional*, defaults to 0.0):
                Corresponds to parameter eta (η) from the [DDIM](https://huggingface.co/papers/2010.02502) paper. Only
                applies to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
            generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
                A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
                generation deterministic.
            latents (`torch.Tensor`, *optional*):
                Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for audio
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                tensor is generated by sampling using the supplied random `generator`.
            initial_audio_waveforms (`torch.Tensor`, *optional*):
                Optional initial audio waveforms to use as the initial audio waveform for generation. Must be of shape
                `(batch_size, num_channels, audio_length)` or `(batch_size, audio_length)`, where `batch_size`
                corresponds to the number of prompts passed to the model.
            initial_audio_sampling_rate (`int`, *optional*):
                Sampling rate of the `initial_audio_waveforms`, if they are provided. Must be the same as the model.
            prompt_embeds (`torch.Tensor`, *optional*):
                Pre-computed text embeddings from the text encoder model. Can be used to easily tweak text inputs,
                *e.g.* prompt weighting. If not provided, text embeddings will be computed from `prompt` input
                argument.
            negative_prompt_embeds (`torch.Tensor`, *optional*):
                Pre-computed negative text embeddings from the text encoder model. Can be used to easily tweak text
                inputs, *e.g.* prompt weighting. If not provided, negative_prompt_embeds will be computed from
                `negative_prompt` input argument.
            attention_mask (`torch.LongTensor`, *optional*):
                Pre-computed attention mask to be applied to the `prompt_embeds`. If not provided, attention mask will
                be computed from `prompt` input argument.
            negative_attention_mask (`torch.LongTensor`, *optional*):
                Pre-computed attention mask to be applied to the `negative_text_audio_duration_embeds`.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
                plain tuple.
            callback (`Callable`, *optional*):
                A function that calls every `callback_steps` steps during inference. The function is called with the
                following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
            callback_steps (`int`, *optional*, defaults to 1):
                The frequency at which the `callback` function is called. If not specified, the callback is called at
                every step.
            output_type (`str`, *optional*, defaults to `"pt"`):
                The output format of the generated audio. Choose between `"np"` to return a NumPy `np.ndarray` or
                `"pt"` to return a PyTorch `torch.Tensor` object. Set to `"latent"` to return the latent diffusion
                model (LDM) output.

        Examples:

        Returns:
            [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
                otherwise a `tuple` is returned where the first element is a list with the generated audio.
        """
        # 0. Convert audio input length from seconds to latent length
        downsample_ratio = self.vae.hop_length

        max_audio_length_in_s = self.transformer.config.sample_size * downsample_ratio / self.vae.config.sampling_rate
        if audio_end_in_s is None:
            audio_end_in_s = max_audio_length_in_s

        if audio_end_in_s - audio_start_in_s > max_audio_length_in_s:
            raise ValueError(
                f"The total audio length requested ({audio_end_in_s - audio_start_in_s}s) is longer than the model maximum possible length ({max_audio_length_in_s}). Make sure that 'audio_end_in_s-audio_start_in_s<={max_audio_length_in_s}'."
            )

        waveform_start = int(audio_start_in_s * self.vae.config.sampling_rate)
        waveform_end = int(audio_end_in_s * self.vae.config.sampling_rate)
        waveform_length = int(self.transformer.config.sample_size)

        # 1. Check inputs. Raise error if not correct
        self.check_inputs(
            prompt,
            audio_start_in_s,
            audio_end_in_s,
            callback_steps,
            negative_prompt,
            prompt_embeds,
            negative_prompt_embeds,
            attention_mask,
            negative_attention_mask,
            initial_audio_waveforms,
            initial_audio_sampling_rate,
        )

        # 2. Define call parameters
        if prompt is not None and isinstance(prompt, str):
            batch_size = 1
        elif prompt is not None and isinstance(prompt, list):
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]

        device = self._execution_device
        # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
        # of the Imagen paper: https://huggingface.co/papers/2205.11487 . `guidance_scale = 1`
        # corresponds to doing no classifier free guidance.
        do_classifier_free_guidance = guidance_scale > 1.0

        # 3. Encode input prompt
        prompt_embeds = self.encode_prompt(
            prompt,
            device,
            do_classifier_free_guidance,
            negative_prompt,
            prompt_embeds,
            negative_prompt_embeds,
            attention_mask,
            negative_attention_mask,
        )

        # Encode duration
        seconds_start_hidden_states, seconds_end_hidden_states = self.encode_duration(
            audio_start_in_s,
            audio_end_in_s,
            device,
            do_classifier_free_guidance and (negative_prompt is not None or negative_prompt_embeds is not None),
            batch_size,
        )

        # Create text_audio_duration_embeds and audio_duration_embeds
        text_audio_duration_embeds = torch.cat(
            [prompt_embeds, seconds_start_hidden_states, seconds_end_hidden_states], dim=1
        )

        audio_duration_embeds = torch.cat([seconds_start_hidden_states, seconds_end_hidden_states], dim=2)

        # In case of classifier free guidance without negative prompt, we need to create unconditional embeddings and
        # to concatenate it to the embeddings
        if do_classifier_free_guidance and negative_prompt_embeds is None and negative_prompt is None:
            negative_text_audio_duration_embeds = torch.zeros_like(
                text_audio_duration_embeds, device=text_audio_duration_embeds.device
            )
            text_audio_duration_embeds = torch.cat(
                [negative_text_audio_duration_embeds, text_audio_duration_embeds], dim=0
            )
            audio_duration_embeds = torch.cat([audio_duration_embeds, audio_duration_embeds], dim=0)

        bs_embed, seq_len, hidden_size = text_audio_duration_embeds.shape
        # duplicate audio_duration_embeds and text_audio_duration_embeds for each generation per prompt, using mps friendly method
        text_audio_duration_embeds = text_audio_duration_embeds.repeat(1, num_waveforms_per_prompt, 1)
        text_audio_duration_embeds = text_audio_duration_embeds.view(
            bs_embed * num_waveforms_per_prompt, seq_len, hidden_size
        )

        audio_duration_embeds = audio_duration_embeds.repeat(1, num_waveforms_per_prompt, 1)
        audio_duration_embeds = audio_duration_embeds.view(
            bs_embed * num_waveforms_per_prompt, -1, audio_duration_embeds.shape[-1]
        )

        # 4. Prepare timesteps
        self.scheduler.set_timesteps(num_inference_steps, device=device)
        timesteps = self.scheduler.timesteps

        # 5. Prepare latent variables
        # num_channels_vae = self.transformer.config.in_channels
        # latents = self.prepare_latents(
        #     batch_size * num_waveforms_per_prompt,
        #     num_channels_vae,
        #     waveform_length,
        #     text_audio_duration_embeds.dtype,
        #     device,
        #     generator,
        #     latents,
        #     initial_audio_waveforms,
        #     num_waveforms_per_prompt,
        #     audio_channels=self.vae.config.audio_channels,
        # )

        # 6. Prepare extra step kwargs
        extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)

        # 7. Prepare rotary positional embedding
        rotary_embedding = get_1d_rotary_pos_embed(
            self.rotary_embed_dim,
            latents.shape[2] + audio_duration_embeds.shape[1],
            use_real=True,
            repeat_interleave_real=False,
        )

        # 给去噪scheduler初始化 方便null-text-inversion
        self.denoise_scheduler.set_timesteps(num_inference_steps, device=device)
        if hasattr(self.denoise_scheduler, "_step_index"):
            self.denoise_scheduler._step_index = 0
            
        # 8. Denoising loop
        num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
        with self.progress_bar(total=num_inference_steps) as progress_bar:
            for i, t in enumerate(timesteps):
                """原版代码
                # expand the latents if we are doing classifier free guidance
                latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
                latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)

                # predict the noise residual
                noise_pred = self.transformer(
                    latent_model_input,
                    t.unsqueeze(0),
                    encoder_hidden_states=text_audio_duration_embeds,
                    global_hidden_states=audio_duration_embeds,
                    rotary_embedding=rotary_embedding,
                    return_dict=False,
                )[0]

                # perform guidance
                if do_classifier_free_guidance:
                    noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
                    noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

                # compute the previous noisy sample x_t -> x_t-1 (DDIM step)
                latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
                """
                """renoise start"""
                print("denoise_sched._step_index (after reset):", getattr(self.denoise_scheduler, "_step_index", None))

                all_latents = [latents.clone()]
                latents = self.inversion_step(
                        latents,
                        t,
                        prompt_embeds,
                        num_renoise_steps= 5,
                        generator=generator,
                        # transformer参数
                        do_classifier_free_guidance = do_classifier_free_guidance,
                        encoder_hidden_states=text_audio_duration_embeds,
                        global_hidden_states=audio_duration_embeds,
                        rotary_embedding=rotary_embedding,
                        guidance_scale = guidance_scale,
                        num_inference_steps = num_inference_steps,
                        device = device,
                        extra_step_kwargs = extra_step_kwargs
                    )
                    
                all_latents.append(latents.clone())
                """renoise end"""

                
                # call the callback, if provided
                if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
                    progress_bar.update()
                    if callback is not None and i % callback_steps == 0:
                        step_idx = i // getattr(self.scheduler, "order", 1)
                        callback(step_idx, t, latents)

                if XLA_AVAILABLE:
                    xm.mark_step()


        # 9. Post-processing
        if not output_type == "latent":
            audio = self.vae.decode(latents).sample
        else:
            return AudioPipelineOutput(audios=latents)

        audio = audio[:, :, waveform_start:waveform_end]

        if output_type == "np":
            audio = audio.cpu().float().numpy()

        self.maybe_free_model_hooks()

        if not return_dict:
            return (audio,)

        return AudioPipelineOutput(audios=audio)

    def inversion_step(
        self,  # 扩散模型管道
        z_t: torch.tensor,  # 时间步t的噪声潜在表示 相当于latents,t从0开始（从x_0->x_t）
        t: torch.tensor,  # 当前时间步
        prompt_embeds,  # 文本提示的嵌入表示
        added_cond_kwargs = None,  # 附加条件参数（如文本嵌入和时间ID）
        num_renoise_steps: int = 100,  # 重噪声步骤数
        first_step_max_timestep: int = 250,  # 区分第一步和其他步骤的时间步阈值
        generator=None,  # 随机数生成器
        # transformer参数
        do_classifier_free_guidance = None,
        encoder_hidden_states=None,
        global_hidden_states=None,
        rotary_embedding = None,
        guidance_scale = 7,
        num_inference_steps = 100,
        device = None,
        extra_step_kwargs = None
    ) -> torch.tensor:
        """
        执行扩散模型的反转步骤，使用噪声正则化来提高重建质量。
        这是DDIM反转的增强版本，包含多步噪声优化和平均。
        """
        self.print_test(z_t, "输入/z_t")
        self.print_test(t, "输入/t")
        # 保存原始数据类型
        original_dtype = z_t.dtype
        
        # 转换为32位float
        z_t = z_t.float()
        t = t.float()
        if encoder_hidden_states is not None:
            encoder_hidden_states = encoder_hidden_states.float()
        if global_hidden_states is not None:
            global_hidden_states = global_hidden_states.float()
        if rotary_embedding is not None:
            rotary_embedding = tuple(x.to(torch.float32) for x in rotary_embedding)

        average_latent_estimations = True
        
        # 根据当前时间步选择平均范围
        avg_range = (0, 5) if t.item() < first_step_max_timestep else (8, 10)

        nosie_pred_avg = None  # 用于存储平均噪声预测
        noise_pred_optimal = None  # 用于存储"最优"噪声参考
        
        # 通过前向加噪过程计算"真实"的下一时间步潜在表示 原版renosie并没有真正实现部分(猜测相当于)
        # z_tp1_forward = self.scheduler.add_noise(self.z_0, self.noise, t.view((1))).detach()
        # 这里相当于原版inversion的加噪部分
        noise_pred = self.unet_pass(z_t, t,
                do_classifier_free_guidance = do_classifier_free_guidance, # 反演为false（0）
                encoder_hidden_states = encoder_hidden_states,
                global_hidden_states = global_hidden_states,
                rotary_embedding = rotary_embedding
        )
        self.print_test(noise_pred, "noise_pred/首次预测噪声")
        
        # perform guidance
        if do_classifier_free_guidance:
            noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
            noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

        z_tp1_forward = self.scheduler.step(noise_pred, t, z_t, **extra_step_kwargs).prev_sample # 加噪
        self.print_test(z_tp1_forward, "z_tp1_forward/首次加噪后z_t+1")
        
        # 初始化近似下一时间步的潜在表示
        approximated_z_tp1 = z_t.clone()
        
        # 多步重噪声优化循环
        for i in range(num_renoise_steps + 1):
            with torch.no_grad():  # 禁用梯度计算以提高效率
                print("i:", i)
                # 如果启用了噪声正则化且是第一步，需要扩展批次大小
                if i == 0: #  and self.cfg.noise_regularization_num_reg_steps > 0 
                    # 连接前向计算的潜在表示和当前近似值
                    approximated_z_tp1 = torch.cat([z_tp1_forward, approximated_z_tp1])
                    print(f"扩展后 approximated_z_tp1 shape: {approximated_z_tp1.shape}")
                    self.print_test(approximated_z_tp1[0], "扩展后/approximated_z_tp1[0]=z_tp1_forward=加噪后")
                    self.print_test(approximated_z_tp1[1], "扩展后/approximated_z_tp1[1]=approximated_z_tp1=z_t")
                    # 扩展提示嵌入
                    negative_text_audio_duration_embeds_in = torch.zeros_like(
                        encoder_hidden_states, device=encoder_hidden_states.device
                    ).float()  # 确保为float32
                    encoder_hidden_states_in = torch.cat(
                        [negative_text_audio_duration_embeds_in, encoder_hidden_states], dim=0
                    )
                    global_hidden_states_in = torch.cat([global_hidden_states, global_hidden_states], dim=0)
                else:
                    encoder_hidden_states_in = encoder_hidden_states
                    global_hidden_states_in = global_hidden_states
                #   prompt_embeds_in = prompt_embeds
                #   added_cond_kwargs_in = added_cond_kwargs

                # 通过UNet获取噪声预测
                noise_pred = self.unet_pass( approximated_z_tp1, t,
                        do_classifier_free_guidance = False, # 这里是两个batch[(z1,to),(z0,to)]
                        encoder_hidden_states = encoder_hidden_states_in,
                        global_hidden_states = global_hidden_states_in,
                        rotary_embedding = rotary_embedding,
                )
                self.print_test(approximated_z_tp1[0], "预测的噪声1/noise_pred[0]=noise_pred_optimal")
                self.print_test(approximated_z_tp1[1], "预测的噪声2/noise_pred[1]=noise_pred")

                # 如果启用了噪声正则化且是第一步，分割批次
                if i == 0: # self.cfg.noise_regularization_num_reg_steps > 0 and
                    # 分割为"最优"噪声和当前噪声预测
                    noise_pred_optimal, noise_pred = noise_pred.chunk(2) # [(z1,to),(z0,to)]
                    
                    # 如果使用分类器自由引导，应用引导尺度
                    if do_classifier_free_guidance:
                        noise_pred_optimal_uncond, noise_pred_optimal_text = noise_pred_optimal.chunk(2)
                        noise_pred_optimal = noise_pred_optimal_uncond + self.guidance_scale * (noise_pred_optimal_text - noise_pred_optimal_uncond)
                    
                    # 分离"最优"噪声参考(无guidance scale的噪声)
                    noise_pred_optimal = noise_pred_optimal.detach()

                # 执行分类器自由引导
                if do_classifier_free_guidance:
                    noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
                    noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)

                # 计算平均噪声预测（在指定范围内）
                if i >= avg_range[0] and i < avg_range[1]:
                    print("计算平均噪声预测")
                    j = i - avg_range[0]
                    if nosie_pred_avg is None:
                        nosie_pred_avg = noise_pred.clone()
                    else:
                        # 累积平均
                        nosie_pred_avg = j * nosie_pred_avg / (j + 1) + noise_pred / (j + 1)

            # 对噪声预测应用正则化（在指定范围或非平均模式下）
            if i >= avg_range[0] or (not average_latent_estimations and i > 0):
                print("对噪声预测应用正则化")
                noise_pred = self.noise_regularization(
                    noise_pred, 
                    noise_pred_optimal, 
                    lambda_kl=0.065, 
                    lambda_ac=20.0, 
                    num_reg_steps=4, 
                    num_ac_rolls=5, 
                    generator=generator
                )
                self.print_test(noise_pred, "正则化后的噪声1/noise_pred[0]=noise_pred_optimal")
            
            # 使用调度器执行加噪（添加的噪声更加的准确）
            # print("denoise_step_index", self.denoise_scheduler._step_index)
            # approximated_z_tp1 = self.denoise_scheduler.step(noise_pred, t, z_t, **extra_step_kwargs, return_dict=False)[0].detach()
            # approximated_z_tp1 = getattr(approximated_z_tp1, "prev_sample", approximated_z_tp1)#approximated_z_tp1
            # print("denoise_step_index", self.denoise_scheduler._step_index)
            print("noise pred shape:", noise_pred.shape)
            self.scheduler._step_index -= 1
            if(self.scheduler._step_index == 0):
                self.scheduler.lower_order_nums -= 1
            approximated_z_tp1 = self.scheduler.step(noise_pred, t, z_t, **extra_step_kwargs) # 加噪
            approximated_z_tp1 = getattr(approximated_z_tp1, "prev_sample", approximated_z_tp1)
            
            self.print_test(approximated_z_tp1, "返回的结果/approximated_z_tp1=z_t - noise_pred")
            
            # 回退 step_index，保证下一次 step 在同一 sigma(i=0时不回退)
            # if i > 0:
            #     self.denoise_scheduler._step_index -= 1

        # 如果启用了潜在估计平均，使用平均噪声执行额外步骤
        average_latent_estimations = False # 暂时不启用
        if average_latent_estimations and nosie_pred_avg is not None:
            nosie_pred_avg = self.noise_regularization(
                nosie_pred_avg, 
                noise_pred_optimal, 
                lambda_kl=0.065, 
                lambda_ac=20.0, 
                num_reg_steps=4, 
                num_ac_rolls=5, 
                generator=generator
            )
            approximated_z_tp1 = self.scheduler.inv_step(nosie_pred_avg, t, z_t, **extra_step_kwargs, return_dict=False)[0].detach()

        # 执行噪声校正（如果启用）
        perform_noise_correction = False # 暂时不启用
        if perform_noise_correction:
            # 再次通过UNet获取噪声预测
            noise_pred = self.unet_pass(approximated_z_tp1, t,
                    do_classifier_free_guidance = None,
                    encoder_hidden_states = encoder_hidden_states,
                    global_hidden_states = global_hidden_states,
                    # rotary_embedding = rotary_embedding
            )

            # 执行分类器自由引导
            if self.do_classifier_free_guidance:
                noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
                noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
            
            # 使用调度器的特殊步骤更新噪声
            self.scheduler.step_and_update_noise(noise_pred, t, approximated_z_tp1, z_t, return_dict=False, optimize_epsilon_type=self.cfg.perform_noise_correction)

        # 转换回原始数据类型
        return approximated_z_tp1.to(original_dtype)


    @torch.no_grad()
    def unet_pass(self,z_t, t,
                do_classifier_free_guidance = None,
                encoder_hidden_states = None,
                global_hidden_states = None,
                rotary_embedding = None
    ):
        """
        辅助函数：通过UNet进行前向传递，处理分类器自由引导和输入缩放。+ 分类引导
        """
        print("CFG",do_classifier_free_guidance)
        # 确保输入为float32
        z_t = z_t.float()
        t = t.float()
        if encoder_hidden_states is not None:
            encoder_hidden_states = encoder_hidden_states.float()
        if global_hidden_states is not None:
            global_hidden_states = global_hidden_states.float()
        if rotary_embedding is not None:
            rotary_embedding = tuple(x.to(torch.float32) for x in rotary_embedding)
        model_was_fp16 = next(self.transformer.parameters()).dtype == torch.float16
        if model_was_fp16:
            print("[dtype] transformer is half: temporarily converting transformer to float32 for null-text optimization.")
            self.transformer.to(torch.float32)
        
        # 如有需要 扩展batch
        if do_classifier_free_guidance:
            negative_text_audio_duration_embeds = torch.zeros_like(
                encoder_hidden_states, device=encoder_hidden_states.device
            ).float()  # 确保为float32
            encoder_hidden_states = torch.cat(
                [negative_text_audio_duration_embeds, encoder_hidden_states], dim=0
            )
            global_hidden_states = torch.cat([global_hidden_states, global_hidden_states], dim=0)
        
        # 如果需要分类器自由引导，复制输入
        latent_model_input = torch.cat([z_t] * 2) if do_classifier_free_guidance else z_t
        # 根据调度器缩放模型输入
        latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)


        # # test
        # print("t dtype:", t.dtype)
        # print("z_t:", z_t.shape, z_t.dtype, z_t.device)
        # print("encoder_hidden_states:", encoder_hidden_states.shape, encoder_hidden_states.dtype, encoder_hidden_states.device)
        # print("global_hidden_states:", global_hidden_states.shape, global_hidden_states.dtype, global_hidden_states.device)
        # print("rotary_embedding[0]:", rotary_embedding[0].shape, rotary_embedding[0].dtype, rotary_embedding[0].device)
        # # 检查 transformer 的参数精度
        # for name, param in self.transformer.named_parameters():
        #     print(f"transformer param {name}: {param.dtype}")
        #     break  # 打印一个就够，确认是不是 half

        # predict the noise residual
        noise_pred = self.transformer(
            latent_model_input,
            t.unsqueeze(0),
            encoder_hidden_states=encoder_hidden_states,
            global_hidden_states=global_hidden_states,
            rotary_embedding=rotary_embedding,
            return_dict=False,
        )[0]
        
        return noise_pred
        
    # 基于 https://github.com/pix2pixzero/pix2pix-zero 的代码
    def noise_regularization(
        self,
        e_t,  # 当前步骤预测的噪声
        noise_pred_optimal,  # "最优"参考噪声（通常来自前向加噪过程）
        lambda_kl,  # KL散度正则化的权重系数
        lambda_ac,  # 自相关正则化的权重系数
        num_reg_steps,  # 正则化步骤的总数
        num_ac_rolls,  # 自相关损失计算的滚动次数
        generator=None  # 随机数生成器，用于可重复的随机性
    ):
        """
        对预测的噪声应用正则化，通过KL散度和自相关损失来优化噪声估计。
        这个过程通过梯度下降迭代地改进噪声预测。
        """
        # 保存原始数据类型
        original_dtype = e_t.dtype
        # 转换为float32进行计算
        e_t = e_t.float()
        if noise_pred_optimal is not None:
            noise_pred_optimal = noise_pred_optimal.float()
            
        # 正则化前输入检查
        print("noise_regularization:正则化输入检查")
        self.print_test(e_t, "e_t")
        self.print_test(noise_pred_optimal, "noise_pred_optimal")
        
        # 执行多步正则化优化
        for _outer in range(num_reg_steps): # 通常为4步
            # KL散度正则化：确保预测噪声的分布与"最优"噪声分布相似
            if lambda_kl > 0 and noise_pred_optimal is not None:
                # 创建需要梯度的变量副本
                _var = torch.autograd.Variable(e_t.detach().clone(), requires_grad=True)
                # 计算KL散度损失
                l_kld = self.patchify_latents_kl_divergence(_var, noise_pred_optimal)
                # 反向传播计算梯度
                l_kld.backward()
                # 获取梯度并剪裁以防止梯度爆炸
                _grad = _var.grad.detach()
                _grad = torch.clip(_grad, -100, 100)
                # 使用梯度下降更新噪声估计
                e_t = e_t - lambda_kl * _grad
            
            # 自相关正则化：减少噪声中的周期性模式
            if lambda_ac > 0:
                # 多次计算自相关损失以获得更稳定的梯度估计
                total_ac_loss = 0.0
                for _inner in range(num_ac_rolls):
                    # 创建需要梯度的变量副本
                    _var = torch.autograd.Variable(e_t.detach().clone(), requires_grad=True)
                    # 计算自相关损失
                    l_ac = self.auto_corr_loss(_var, generator=generator)
                    current_loss = l_ac.item()
                    total_ac_loss += current_loss
                    # 反向传播计算梯度
                    l_ac.backward()
                    # 获取梯度并平均（因为有多轮滚动）
                    _grad = _var.grad.detach() / num_ac_rolls
                    # 使用梯度下降更新噪声估计
                    e_t = e_t - lambda_ac * _grad
                    print(f"  AC[{_inner+1}]: loss={current_loss:.4f}, grad_norm={_grad.norm().item():.4f}")
            # 添加print
            avg_loss = total_ac_loss / num_ac_rolls
            print(f"自相关正则化完成 - 平均损失: {avg_loss:.4f}")
            
            # 分离计算图，防止梯度累积
            e_t = e_t.detach()

        # 转换回原始数据类型
        return e_t.to(original_dtype)


    # 基于 https://github.com/pix2pixzero/pix2pix-zero 的代码
    def auto_corr_loss(
            self,
            x,  # 输入张量 [B, C, T] - 音频数据
            random_shift=True,  # 是否使用随机位移
            generator=None  # 随机数生成器
    ):
        """
        计算音频数据的自相关损失，用于减少噪声中的周期性模式。
        适配音频的3维结构 [batch, channels, time]
        """
        # 保存原始数据类型并转换为float32
        original_dtype = x.dtype
        x = x.float()
        
        B, C, T = x.shape  # 音频维度: 批次, 通道, 时间
        
        reg_loss = 0.0  # 初始化损失值
        
        # 对每个批次和通道分别处理
        for batch_idx in range(B):
            for ch_idx in range(C):
                # 提取当前通道的时间序列 [T]
                audio_signal = x[batch_idx, ch_idx]
                
                # 在多尺度上计算自相关损失
                current_signal = audio_signal.unsqueeze(0).unsqueeze(0)  # [1, 1, T]
                
                while True:
                    # 随机选择位移量或使用固定位移
                    if random_shift:
                        # 在时间维度上随机位移
                        max_shift = max(1, current_signal.shape[2] // 2)
                        roll_amount = torch.randint(0, max_shift, (1,), generator=generator).item()
                    else:
                        roll_amount = 1
                    
                    # 计算时间方向的自相关（音频只有时间维度）
                    shifted_signal = torch.roll(current_signal, shifts=roll_amount, dims=2)
                    correlation = (current_signal * shifted_signal).mean()
                    reg_loss += correlation ** 2  # 平方使损失为正
                    
                    # 当信号长度太小时停止多尺度处理
                    if current_signal.shape[2] <= 8:
                        break
                    
                    # 使用平均池化进行时间维度下采样
                    # 将 [1, 1, T] 转换为 [1, 1, 1, T] 以适应 avg_pool2d
                    signal_4d = current_signal.unsqueeze(2)  # [1, 1, 1, T]
                    # 在时间维度上进行池化 (kernel_size=2, 步长=2)
                    pooled_signal = F.avg_pool2d(signal_4d, kernel_size=(1, 2), stride=(1, 2))
                    current_signal = pooled_signal.squeeze(2)  # 恢复为3维 [1, 1, T/2]
        
        # 转换回原始数据类型
        return reg_loss.to(original_dtype)


    def patchify_latents_kl_divergence(self, x0, x1, patch_size=4, num_channels=None):
        """
        将音频潜在表示分割成时间块，然后计算块之间的KL散度。
        """
        # 转换为float32进行计算
        original_dtype = x0.dtype
        x0 = x0.float()
        x1 = x1.float()
        
        # 自动检测通道数
        if num_channels is None:
            num_channels = x0.shape[1]
        
        def patchify_audio_tensor(input_tensor):
            """
            将3D音频张量分割成时间块。
            input_tensor: [B, C, T]
            """
            B, C, T = input_tensor.shape
            
            # 确保时间长度可以被patch_size整除
            T_patches = T // patch_size
            if T % patch_size != 0:
                # 如果无法整除，进行裁剪
                T_target = T_patches * patch_size
                input_tensor = input_tensor[:, :, :T_target]
            
            # 使用unfold在时间维度上提取patch
            # unfold在维度2（时间）上操作，patch_size大小，步长patch_size
            patches = input_tensor.unfold(2, patch_size, patch_size)  # [B, C, num_patches, patch_size]
            
            # 重新整形为 [num_patches, channels, patch_size]
            patches = patches.permute(0, 2, 1, 3).contiguous()  # [B, num_patches, C, patch_size]
            patches = patches.view(-1, C, patch_size)  # [B*num_patches, C, patch_size]
            
            return patches

        # 将两个输入张量都分割成时间块
        x0_patches = patchify_audio_tensor(x0)
        x1_patches = patchify_audio_tensor(x1)

        # 计算时间块之间的KL散度并求和
        kl = self.latents_kl_divergence(x0_patches, x1_patches).sum()
        # 转换回原始数据类型
        return kl.to(original_dtype)

    def latents_kl_divergence(self, x0, x1):
        """
        计算两个音频潜在表示集合之间的KL散度。
        适配音频的3维结构。
        """
        # 确保输入为float32
        x0 = x0.float()
        x1 = x1.float()
        
        EPSILON = 1e-6  # 小常数防止数值不稳定
        
        # 确保输入形状一致
        assert x0.shape == x1.shape, f"Shape mismatch: {x0.shape} vs {x1.shape}"
        
        # 对于音频，我们通常在时间维度上计算统计量
        # x0, x1: [N, C, T] 其中N是patch数量，C是通道数，T是时间长度
        
        # 计算均值和方差（在时间维度上）
        mu0 = x0.mean(dim=-1)  # [N, C] - 每个patch每个通道的均值
        mu1 = x1.mean(dim=-1)  # [N, C]
        var0 = x0.var(dim=-1, unbiased=False)  # [N, C] - 每个patch每个通道的方差
        var1 = x1.var(dim=-1, unbiased=False)  # [N, C]
        
        # 计算KL散度公式（高斯分布假设）
        kl = (
            torch.log((var1 + EPSILON) / (var0 + EPSILON))  # 对数方差比
            + (var0 + (mu0 - mu1) ** 2) / (var1 + EPSILON)  # 均值差和方差项
            - 1  # 常数项
        )
        
        # 对通道维度求和，然后对所有patch取平均
        kl = kl.sum(dim=-1).mean()  # 先对通道求和得到[N]，然后平均
        
        return kl
    
    def print_test(self, a, name):
        print(f"[调试统计]【{name} 】： min={a.min().item():.6f}, max={a.max().item():.6f}")